<template>
  <el-card style="height: 100%">
    <!-- 1.面包屑 -->
    <MyBread url="coach" level1="车辆预定" />
    <!-- 2.搜索 -->
    <el-input
      placeholder="请输入车牌号"
      v-model="search"
      class="with-input"
      clearable
    >
      <el-button
        slot="append"
        icon="el-icon-search"
        @click="searchUser"
      ></el-button>
    </el-input>
    <!-- 5.预约车辆 -->
    <el-button type="success" @click="cancelBookedVehicle" round
      >取消已预约车辆</el-button
    >
    <el-button type="success" @click="checkBookedVehicle" round
      >查看已预约车辆信息</el-button
    >
    <!-- 3.表格 -->
    <el-table
      ref="NotUseCarTable"
      :data="NoReversedVehicle"
      style="width: 100%"
      highlight-current-row
      @row-click="handleRowClickTable"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="carNumber" label="车辆名"></el-table-column>
      <el-table-column prop="logonDate" label="注册日期"></el-table-column>
      <el-table-column prop="insuranceDate" label="保险日期"></el-table-column>
      <el-table-column prop="validDate" label="有效日期"></el-table-column>
      <el-table-column prop="scrapDate" label="报废日期"></el-table-column>
      <el-table-column prop="appointDate" label="预约日期"></el-table-column>
      <el-table-column prop="useCount" label="使用次数"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isUse"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="已预约"
            inactive-text="未预约"
            disabled
            class="switch"
          ></el-switch>
        </template>
      </el-table-column>
    </el-table>
    <!-- 4.分页 -->
    <el-pagination
      style="margin-top: 30px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[2, 4, 6, 8]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="length"
    ></el-pagination>
    <!-- 6.对话框 -->
    <el-dialog
      title="预约车辆信息"
      :visible.sync="dialogFormVisible"
      width="440"
    >
      <el-form
        :model="AppointCarInfo"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="车牌号">
          <el-input v-model="AppointCarInfo.carNumber" readonly></el-input>
        </el-form-item>
        <el-form-item label="注册日期">
          <el-date-picker
            format="yyyy-MM-dd"
            style="width: 100%"
            v-model="AppointCarInfo.logonDate"
            readonly
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="保险日期">
          <el-date-picker
            format="yyyy-MM-dd"
            style="width: 100%"
            v-model="AppointCarInfo.insuranceDate"
            readonly
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="有效日期">
          <el-date-picker
            format="yyyy-MM-dd"
            style="width: 100%"
            v-model="AppointCarInfo.validDate"
            readonly
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="报废日期">
          <el-date-picker
            format="yyyy-MM-dd"
            style="width: 100%"
            v-model="AppointCarInfo.scrapDate"
            readonly
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="预约日期">
          <el-date-picker
            format="yyyy-MM-dd"
            style="width: 100%"
            v-model="AppointCarInfo.appointDate"
            readonly
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="使用次数">
          <el-input v-model="AppointCarInfo.useCount" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible = false"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "CarReserve",
  data() {
    return {
      search: "", // 搜索字符搜集
      length: 0, // 数据长度
      limit: 2, // 每页显示记录数量
      page: 1, // 当前页数
      NoReversedVehicle: [], // 未被预约车辆
      dialogFormVisible: false, // 控制表单对话框的显隐
      AppointCarInfo: {}, // 预约车辆信息
    };
  },
  methods: {
    // 获取未预约车辆长度
    async getAllCarLength() {
      this.length = (
        await this.$store.dispatch("CoachModule/getAllCarInfo", {
          like: this.search,
          isUse: false,
        })
      ).length;
    },
    // 搜索功能实现 -- 搜索车辆
    searchUser() {
      this.getAllCarLength();
      // 获取搜索后的数据
      this.limit = 2;
      this.page = 1;
      this.getNoReversedCarInfo();
      this.search = "";
    },
    // 获取未被使用车辆数据
    async getNoReversedCarInfo() {
      this.NoReversedVehicle = await this.$store.dispatch(
        "CoachModule/getAllCarInfo",
        {
          page: this.page,
          limit: this.limit,
          like: this.search,
          isUse: false,
        }
      );
    },
    // 当每页条数发生变化使调用
    handleSizeChange(val) {
      this.limit = val;
      this.page = 1;
      this.getNoReversedCarInfo();
    },
    // 当页数发生变化时调用
    handleCurrentChange(val) {
      this.page = val;
      this.getNoReversedCarInfo();
    },
    // 处理选中的车辆
    async handleRowClickTable(row) {
      if (!(await this.haveThisPermission(this.$route.path, "教练预约车辆"))) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      if (this.CurrentCoachInfo.reverseCar === "") {
        // 弹出确认框确定是否选中该辆车
        this.$confirm("是否确认预约该车辆?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            // 修改预约辆信息 -- 状态
            row.isUse = true;
            // 添加预约时间 -- 只能预约第二天
            let date = new Date().getTime() + 3600 * 1000 * 24;
            date = new Date(date);
            row.appointDate =
              date.getFullYear() +
              "-" +
              (date.getMonth() + 1) +
              "-" +
              date.getDate();
            // 修改车辆使用次数
            row.useCount++;

            // 修改数据库数据 -- cars
            await this.$https.updateUserData("/cars", row.id, row);
            this.AppointCarInfo = row; // 为取消预约做准备
            // 修改预约教练的信息 -- reverseCar
            this.CurrentCoachInfo.reverseCar = row.carNumber;
            await this.$https.updateUserData(
              "/coach",
              this.CurrentCoachInfo.id,
              this.CurrentCoachInfo
            );
            this.$message.success("已预约该车辆!");
            // 重新加载数据
            this.getAllCarLength();
            this.getNoReversedCarInfo();
          })
          .catch(() => {
            this.$message.info("已取消预约");
          });
      } else {
        this.$message.info("已预约车辆");
      }
    },
    // 取消已预约的车辆（删除预约）
    async cancelBookedVehicle() {
      if (
        !(await this.haveThisPermission(this.$route.path, "删除教练预约车辆"))
      ) {
        this.$message.warning("您当前没有该权限");
        return;
      }
      if (this.CurrentCoachInfo.reverseCar !== "") {
        // 如果预约的时间已经到了，则不能取消预约
        if (new Date(this.AppointCarInfo.appointDate).getTime() < Date.now()) {
          this.$message.info("预约时间已到，不能取消预约");
          return;
        }
        this.$confirm("是否取消预约?", "提示", {
          confirmButtonText: "确定", // 取消预约
          cancelButtonText: "取消", // 什么都不做
          type: "warning",
        })
          .then(async () => {
            // 取消预约 -- 设置状态
            this.AppointCarInfo.isUse = false;
            this.AppointCarInfo.appointDate = "";
            this.AppointCarInfo.useCount--;
            // 修改数据库数据
            await this.$https.updateUserData(
              "/cars",
              this.AppointCarInfo.id,
              this.AppointCarInfo
            );
            // 修改数据库【车辆】数据成功 -- 表示取消预约
            this.AppointCarInfo = {}; // 预约车辆信息置空
            // 修改预约教练的信息 -- reverseCar
            this.CurrentCoachInfo.reverseCar = "";
            await this.$https.updateUserData(
              "/coach",
              this.CurrentCoachInfo.id,
              this.CurrentCoachInfo
            );
            // 修改数据库【教练】数据成功
            this.$message.success("已取消预约该车辆!");
            // 重新加载数据
            this.getAllCarLength();
            this.getNoReversedCarInfo();
          })
          .catch(() => {
            this.$message.info("已取消该操作");
          });
      } else {
        this.$message.info("暂未预约车辆");
      }
    },
    // 查看已预约车辆
    checkBookedVehicle() {
      if (this.CurrentCoachInfo.reverseCar !== "") {
        // 查看预约 -- 显示对话框
        this.dialogFormVisible = true;
      } else {
        this.$message.info("暂未预约车辆");
      }
    },
  },
  computed: {
    ...mapState("CoachModule", ["CurrentCoachInfo"]),
  },
  async mounted() {
    // 获取登录用户的信息 -- 教练信息
    await this.$store.dispatch("CoachModule/getCurrentCoachInfo");
    // 获取预约车辆信息
    if (this.CurrentCoachInfo.reverseCar !== "") {
      const { data: car } = await this.$https.getCar({
        like: this.CurrentCoachInfo.reverseCar,
      });
      if (car.length !== 0) {
        this.AppointCarInfo = car[0];
      }
    }
    // 新的一天 ==> 对车辆信息重置
    const { data: array } = await this.$https.getCar({});
    array.forEach(async (element) => {
      if (element.isUse && new Date(element.appointDate) < Date.now()) {
        // console.log(`修改id=${element.id}车辆数据`);
        element.appointDate = "";
        element.isUse = false;
        await this.$https.updateUserData("/cars", element.id, element);
        // 获取预约该车辆的教练信息
        const { data } = await this.$https.getCoachInfoByReverseCar(
          element.carNumber
        );
        // console.log(`修改id=${res.data[0].id}教练数据`);
        data[0].reverseCar = "";
        this.$https.updateUserData("/coach", data[0].id, data[0]);
        if (this.CurrentCoachInfo.id === data[0].id) {
          await this.$store.dispatch("CoachModule/getCurrentCoachInfo");
          this.AppointCarInfo = {};
        }
      }
    });
    // 车辆传长度 -- 未使用的
    this.getAllCarLength();
    this.getNoReversedCarInfo();
  },
};
</script>

<style scoped>
.with-input {
  width: 500px;
  margin-top: 30px;
  margin-bottom: 30px;
  margin-right: 10px;
}
</style>